/* ***********************
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is WriteFeatures.js module.
 *
 * The Initial Developer of the Original Code is Rob Gerns.
 *
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 **************************/

/***********************************************
* Function Name(s): getFeatures; writeFeatureSetup, writeFeature
*
* Purpose:
* Use AJAX to read the Oister XML file, grab all 
* of the features in the file and all child elements
* of each feature, display everything accordingly.
* Also hides features that have an expired showuntil
* datetime and displays features according to 
* priority.
************************************************/

function getFeatures(xmlDocument){

 //All feature elements (this is actually an array)
 var features = xmlDocument.getElementsByTagName("feature");  	
 
 //Count how many feature elements exist in the document
 var featuresCount = features.length;						
	
 //Check to see if there is at least 1 feature element before continuing 
 if(featuresCount > 0){
	    
  //Set up a loop so that every feature is read 
  for(var i=0;i<featuresCount;i++){
    
   //the feature in the Oister file that the loop is currently working on  
	 currentFeature = features[i];  	
	 
	 //the value of the required "priority" attribute of the current feature element   
	 currentFeaturePriority = currentFeature.getAttribute("priority");
	 
	 //check to see if the "hidepriority" attribute is set (it's optional)
	 if(currentFeature.getAttribute!=null && currentFeature.getAttribute!=undefined){
		
		currentFeatureHidePriority = currentFeature.getAttribute("hidepriority"); //value of the "hidepriority" attribute
		
	  }
	  //if it's not set, set the hidepriority value to the default (false)
		else currentFeatureHidePriority = "false"; 
			
    
    if(currentFeature.getElementsByTagName("title")[0]!=null && currentFeature.getElementsByTagName("title")[0]!=undefined){
			
		 //current feature's title, this element is required in the Oister file	
		 featureTitle = currentFeature.getElementsByTagName("title")[0].firstChild.nodeValue;
		
		}
    else featureTitle = "";

    
    if(currentFeature.getElementsByTagName("description")[0]!=null && currentFeature.getElementsByTagName("description")[0]!=undefined){
		 
		 if(currentFeature.getElementsByTagName("description")[0].firstChild.nodeValue!="" && currentFeature.getElementsByTagName("description")[0].firstChild.nodeValue!="<![CDATA[]]>"){
			
			//current feature's description, also required  
			featureDesc = currentFeature.getElementsByTagName("description")[0].firstChild.nodeValue; 			
		 }
		
		}
    else featureDesc = "";
			
			
	  /* Most of the rest of the feature's possible elements are optional, so there's an
		 * if/else for them to make sure the corresponding variables get set to blank if 
		 * the child element doesn't exist in the XML. Otherwise, the variables would 
		 * either be undefined or retain the value assigned in a previous loop iteration */ 
			
		//Get any contact information
		if(currentFeature.getElementsByTagName("contact")[0] != null && currentFeature.getElementsByTagName("contact")[0] !=undefined){
		 featureContact = currentFeature.getElementsByTagName("contact")[0].firstChild.nodeValue;
		}
		else featureContact = "";
			
		//Get the link to the feature 
		if(currentFeature.getElementsByTagName("featurelink")[0]!= null && currentFeature.getElementsByTagName("featurelink")[0] !=undefined){
		 featureLink = currentFeature.getElementsByTagName("featurelink")[0].firstChild.nodeValue;
		}
		else featureLink = "";
			
		//Get any tags
		if(currentFeature.getElementsByTagName("tags")[0] != null && currentFeature.getElementsByTagName("tags")[0]!=undefined){
		 featureTags = currentFeature.getElementsByTagName("tags")[0].firstChild.nodeValue;
		}
		else featureTags = "";
			
		//Get any map info
		if(currentFeature.getElementsByTagName("map")[0]!=null && currentFeature.getElementsByTagName("map")[0]!=undefined){
		 featureMap = currentFeature.getElementsByTagName("map")[0].firstChild.nodeValue;
		}
		else featureMap = "";
			
		//Get the name of the feature's author (there's just one author, anyone else is a contributor)
		if(currentFeature.getElementsByTagName("author")[0] != null && currentFeature.getElementsByTagName("author")[0]!=undefined){
		 featureAuthor = currentFeature.getElementsByTagName("author")[0].firstChild.nodeValue;
		}
		else featureAuthor = "";
			
		//Get the e-mail address of the feature's author
		if(currentFeature.getElementsByTagName("authorEmail")[0]!= null && currentFeature.getElementsByTagName("authorEmail")[0]!=undefined){
		 featureAuthorEmail = currentFeature.getElementsByTagName("authorEmail")[0].firstChild.nodeValue;
		}
		else featureAuthorEmail = "";
			
		//Get the info of any contributors
    if(currentFeature.getElementsByTagName("contributors")[0] != null && currentFeature.getElementsByTagName("contributors")[0]!=undefined){
		 featureContributors = currentFeature.getElementsByTagName("contributors")[0].firstChild.nodeValue;
		}
		else featureContributors = "";
			
		//Get any copyright info
		if(currentFeature.getElementsByTagName("copyright")[0] != null && currentFeature.getElementsByTagName("copyright")[0]!=undefined){
		 featureCopyright = currentFeature.getElementsByTagName("copyright")[0].firstChild.nodeValue;
		}
		else featureCopyright = "";
			
		//Get any extra documentation
		if(currentFeature.getElementsByTagName("documentation")[0] != null && currentFeature.getElementsByTagName("documentation")[0]!=undefined){
		 featureDocumentation = currentFeature.getElementsByTagName("documentation")[0].firstChild.nodeValue;
		}
		else featureDocumentation = "";
			
		//Get any GUID that might be set
		if(currentFeature.getElementsByTagName("guid")[0]!= null && currentFeature.getElementsByTagName("guid")[0]!=undefined){
		 featureGUID = currentFeature.getElementsByTagName("guid")[0].firstChild.nodeValue;
		}
		else featureGUID = "";
			
		//Get the feature's timestamp if it exists
		if(currentFeature.getElementsByTagName("timestamp")[0] != null && currentFeature.getElementsByTagName("timestamp")[0]!=undefined){
		 featureTimestamp = currentFeature.getElementsByTagName("timestamp")[0].firstChild.nodeValue;
		}
		else featureTimestamp = "";
			
		//Get the feature's showuntil datetime if it exists
		if(currentFeature.getElementsByTagName("showuntil")[0]!= null && currentFeature.getElementsByTagName("showuntil")[0]!=undefined){
		 featureShowUntil = currentFeature.getElementsByTagName("showuntil")[0].firstChild.nodeValue;
		}
		else featureShowUntil = "";
			
		//Check to see if there are any images defined
    if(currentFeature.getElementsByTagName("image")[0] != null && currentFeature.getElementsByTagName("image")[0]!=undefined){
				
		 //There are some images, so read in the list
		 featureImages = currentFeature.getElementsByTagName("image");
				
		 //There has to be at least one, so store it
		 featureImageNum0 = featureImages[0];
					
		  //Check to see if the imglink and caption attributes are set
      if(featureImageNum0!=undefined && featureImageNum0!=null){
					
			 featureImageLink0 = featureImages[0].getAttribute("imglink");
			 featureImageCaption0 = featureImages[0].getAttribute("caption");
      }
			else{
			 
			 featureImageNum0 ="";
			 featureImageLink0 ="";
			 featureImageCaption0 ="";
			}
			    
			//Check to see if there's a second image
			featureImageNum1 = featureImages[1];
					
			//Grab the imglink and caption attributes if so 
			if(featureImageNum1!=undefined && featureImageNum1!=null){
			
			 featureImageLink1 = featureImages[1].getAttribute("imglink");
			 featureImageCaption1 = featureImages[1].getAttribute("caption");
					
			}
			else{
					
			 featureImageNum1 ="";
			 featureImageLink1="";
			 featureImageCaption1="";
			}
			
			//Check to see if there's a third image
			featureImageNum2 = featureImages[2];
					
			//Grab the imglink and caption attributes if so
			if(featureImageNum2!=undefined && featureImageNum2!=null){
					
			 featureImageLink2 = featureImages[2].getAttribute("imglink");
			 featureImageCaption2 = featureImages[2].getAttribute("caption");
			}
			else{
					
			 featureImageNum2 ="";
			 featureImageLink2 ="";
			 featureImageCaption2 ="";
			}
		}
		
		//If there are no images with the feature, set all the related image variables to blank values
		else{
				
		 featureImageNum0 ="";
		 featureImageLink0 ="";
		 featureImageCaption0 ="";
		 featureImageNum1 ="";
		 featureImageLink1="";
		 featureImageCaption1="";
		 featureImageNum2 ="";
		 featureImageLink2 ="";
		 featureImageCaption2 ="";
		}
			
    //Check to see if there's a media element in the feature
    if(currentFeature.getElementsByTagName("media")[0] != null && currentFeature.getElementsByTagName("media")[0]!=undefined){
     
     //If so, grab all the related values: type, filesize, filelink
		 featureMedia = currentFeature.getElementsByTagName("media")[0];
		 featureMediaType = featureMedia.getAttribute("type");
		 featureMediaFilesize = featureMedia.getAttribute("filesize");
		 featureMediaLink = featureMedia.getAttribute("filelink");
		}
		
		//If the media element doesn't exist, set all the related variables back to blank values
		else{
			
		 featureMedia="";
		 featureMediaType="";
		 featureMediaFilesize="";
		 featureMediaLink="";
		}
	
    /* Create a one-dimensional array that contains all the variables that were defined above.  
     * Either they'll have the value grabbed from the Oister file or they'll be
	   * set to blank. */
    var featureChildren = new Array();
    featureChildren[0] = featureTitle;
    featureChildren[1] = featureDesc;
    featureChildren[2] = featureImageNum0;
    featureChildren[3] = featureImageLink0;
    featureChildren[4] = featureImageCaption0;
    featureChildren[5] = featureImageNum1;
    featureChildren[6] = featureImageLink1;
    featureChildren[7] = featureImageCaption1;
    featureChildren[8] = featureImageNum2;
    featureChildren[9] = featureImageLink2;
    featureChildren[10] = featureImageCaption2;
    featureChildren[11] = featureContact;
    featureChildren[12] = featureLink;
    featureChildren[13] = featureTags;
    featureChildren[14] = featureMap;
    featureChildren[15] = featureAuthor;
    featureChildren[16] = featureAuthorEmail;
    featureChildren[17] = featureContributors;
    featureChildren[18] = featureCopyright;
    featureChildren[19] = featureDocumentation;
    featureChildren[20] = featureGUID;
    featureChildren[21] = featureTimestamp;
    featureChildren[22] = featureShowUntil;
    featureChildren[23] = featureMediaType;
    featureChildren[24] = featureMediaFilesize;
    featureChildren[25] = featureMediaLink;
			
    /* Call the writeFeatureSetup function and pass along the index number 
	   * of the current feature, the priority level, the hidepriority boolean value,
	   * and the array that contains all the feature's element/attribute values */
  	writeFeatureSetup(i,currentFeaturePriority,currentFeatureHidePriority,featureChildren);

		}

	}

}


function writeFeatureSetup(i,currentFeaturePriority,currentFeatureHidePriority,featureChildren){
	
	/* Check the priority level of the current feature, the call the writeFeature function and pass 
	 * the info along, why not just use currentFeaturePriority in the next function? Because
	 * then it would be necessary to write all the same lines of DOM manipulation in five separate
	 * places in a bunch of if/else ifs.  This way, it's all just in one function and the if/else ifs
	 * are used here instead */
	if(currentFeaturePriority=="highest"){
		writeFeature("highest",i,currentFeaturePriority,currentFeatureHidePriority,featureChildren);
	}
	else if(currentFeaturePriority=="high"){
		writeFeature("high",i,currentFeaturePriority,currentFeatureHidePriority,featureChildren);
	}
	else if(currentFeaturePriority=="normal"){
		writeFeature("normal",i,currentFeaturePriority,currentFeatureHidePriority,featureChildren);
	}
	else if(currentFeaturePriority=="low"){
		writeFeature("low",i,currentFeaturePriority,currentFeatureHidePriority,featureChildren);
	}
	else if(currentFeaturePriority=="lowest"){
		writeFeature("lowest",i,currentFeaturePriority,currentFeatureHidePriority,featureChildren);
	}
	else writeFeature("lowest",i,currentFeaturePriority,currentFeatureHidePriority,featureChildren);
		
}
		
function writeFeature(priorityID,i,currentFeaturePriority,currentFeatureHidePriority,featureChildren){
	
 //A unique ID for the feature node that will be created	
 featureIdNum = "feature"+i;
 
 //capitalize the priority level
 var capitalizePriority = currentFeaturePriority.charAt(0).toUpperCase()+currentFeaturePriority.substring(1);
	
 //create a new node in the DOM that will contain the feature, place it according to priority level
 divFeature = document.createElement("div");
 divFeatureId = divFeature.id = featureIdNum;
 divFeature.className = "feature"+capitalizePriority;
 document.getElementById(priorityID).appendChild(divFeature);
			
 //Double check to make sure the title isn't blank (shouldn't be) and create a node for it
 if(featureChildren[0]!=""){
 
  divFeatureTitle = document.createElement("div");
	divFeatureTitle.id = "title"+i;
	divFeatureTitle.className = "featureTitle";
	divFeature.appendChild(divFeatureTitle);
	divFeatureTitle.innerHTML = featureChildren[0];
 }
			
 //create a node for the author of the feature, if it the author was defined
 if(featureChildren[15]!=""){
  
  divFeatureAuthor = document.createElement("div");
  divFeatureAuthor.id = "author"+i;
  divFeatureAuthor.className = "featureAuthor";
  divFeature.appendChild(divFeatureAuthor);
	divFeatureAuthor.innerHTML = "By "+featureChildren[15];
 }
			
 //create a node fo the author's e-mail, if it was defined
 if(featureChildren[16]!=""){
		
  divFeatureAuthorEmail = document.createElement("div");
	divFeatureAuthorEmail.id = "authorEmail"+i;
	divFeatureAuthorEmail.className = "featureAuthorEmail";
	divFeature.appendChild(divFeatureAuthorEmail);
	divFeatureAuthorEmail.innerHTML = "E-mail the author: "+featureChildren[16];
 }
			
 //create a node to show the priority level, unless "hidepriority" was set to true
 if(currentFeatureHidePriority!="true"){
			
  divFeaturePriority = document.createElement("div");
	divFeaturePriority.id = "priority"+i;
	divFeaturePriority.className = "priority";
	divFeature.appendChild(divFeaturePriority);
	divFeaturePriority.innerHTML = "Priority: "+capitalizePriority;
 }
			
 //check for any images and create the nodes accordingly if any images exist
 if(featureChildren[2]!=""){
	
  for(var j=2; j<11; j+=3){
	 
	 var k = j-2;
		
   if(featureChildren[j]!=""){
			   
	  divFeatureImage[k] = document.createElement("div");
		divFeatureImage[k].id = "div"+featureIdNum+"image"+k;
		divFeatureImage[k].className = "featureImageDiv";
		divFeature.appendChild(divFeatureImage[k]);
		
		var featureImageId = featureIdNum+"image"+k;
		if(featureChildren[j+1]!=null && featureChildren[j+1]!=undefined){
			
		 divFeatureImage[k].innerHTML="<img id=\""+featureImageId+"\" src='"+featureChildren[j+1]+"'>";
		 document.getElementById(featureImageId).className = "featureImage";
		}
		
		if(featureChildren[j+2]!=null && featureChildren[j+2]!=undefined){
						
		 document.getElementById(featureImageId).setAttribute("alt",featureChildren[j+2]);
		}
		
   }
	
  }

 }
			
 //Create a node for the feature's description
 divFeatureDesc = document.createElement("div");
 divFeatureDesc.id = "description"+i;
 divFeatureDesc.className = "description";
 divFeature.appendChild(divFeatureDesc);
 divFeatureDesc.innerHTML = featureChildren[1];
 divFeatureImgBreak = document.createElement("br");
 divFeature.insertBefore(divFeatureImgBreak,divFeatureDesc);
 divFeature.insertBefore(divFeatureImgBreak,divFeatureDesc);
			
			
 //Create a node for any contact info, if the contact info was defined
 if(featureChildren[11]!=""){
			
  divFeatureContact = document.createElement("div");
	divFeatureContact.id = "contact"+i;
	divFeatureContact.className = "featureContact";
	divFeature.appendChild(divFeatureContact);
	divFeatureContact.innerHTML = "Contact: "+featureChildren[11];
 }
			
 //Create a node for the link to the feature, if it exists
 if(featureChildren[12]!=""){
	
  divFeatureLink = document.createElement("div");
	divFeatureLink.id = "featurelink"+i;
	divFeatureLink.className = "featurelink";
	divFeature.appendChild(divFeatureLink);
	divFeatureLink.innerHTML = "Permalink: <a href=\""+featureChildren[12]+"\">"+featureChildren[12]+"</a>";
 }
			
 //Create a node for any contributor info, if the info was defined
 if(featureChildren[17]!=""){
			
  divFeatureContributors = document.createElement("div");
	divFeatureContributors.id = "contributors"+i;
	divFeatureContributors.className = "contributors";
	divFeature.appendChild(divFeatureContributors);
	divFeatureContributors.innerHTML = "Additional Information Provided By "+featureChildren[17];
 }
			
 //Create a node for any tags, if tags were defined
 if(featureChildren[13]!=""){
			
	divFeatureTags = document.createElement("div");
	divFeatureTags.id = "tags"+i;
	divFeatureTags.className = "tags";
  divFeature.appendChild(divFeatureTags);
	divFeatureTags.innerHTML = "Tags: "+featureChildren[13];
 }
			
 //Create a node for a link to any map, if map was defined
 if(featureChildren[14]!=""){
			
  divFeatureMap = document.createElement("div");
  divFeatureMap.id = "map"+i;
	divFeatureMap.className = "map";
	divFeature.appendChild(divFeatureMap);
	divFeatureMap.innerHTML = "Map: <a href=\""+featureChildren[14]+"\">"+featureChildren[14]+"</a>";
 }
			
 //Create a node for any copyright info, if copyright info was defined
 if(featureChildren[18]!=""){
			
  divFeatureCopyright = document.createElement("div");
	divFeatureCopyright.id = "copyright"+i;
	divFeatureCopyright.className = "copyright";
	divFeature.appendChild(divFeatureCopyright);
	divFeatureCopyright.innerHTML = featureChildren[18];
 }
			
 //Create a node for any documentation, if it was defined
 if(featureChildren[19]!=""){
			
  divFeatureDocumentation = document.createElement("div");
  divFeatureDocumentation.id = "documentation"+i;
	divFeatureDocumentation.className = "documentation";
	divFeature.appendChild(divFeatureDocumentation);
	divFeatureDocumentation.innerHTML = featureChildren[19];
 }
			
 //Create a node for any GUID, if it was defined
 if(featureChildren[20]!=""){
			
  divFeatureGUID = document.createElement("div");
  divFeatureGUID.id = "guid"+i;
  divFeatureGUID.className = "guid";
  divFeature.appendChild(divFeatureGUID);
  divFeatureGUID.innerHTML = featureChildren[20];
 }
			
 //Create a node for the feature's timestamp, if it was defined
 if(featureChildren[21]!=""){
			
  divFeatureTimestamp = document.createElement("div");
	divFeatureTimestamp.id = "timestamp"+i;
	divFeatureTimestamp.className = "timestamp";
	divFeature.appendChild(divFeatureTimestamp);
	divFeatureTimestamp.innerHTML = "Created: "+featureChildren[21];
 }
			
 /* Create a node for the showuntil datetime, if was defined.  
	* Also check the showuntil datetime with user's system time 
	* and hide the feature if appropriate (maybe this should be 
	* changed to use a removeNode/destroyNode instead of hiding it?) */
 if(featureChildren[22]!=""){
  
  divFeatureShowuntil = document.createElement("div");
	divFeatureShowuntil.id = "featureshowuntil"+i;
	divFeatureShowuntil.className = "featureShowUntil";
	divFeature.appendChild(divFeatureShowuntil);
	divFeatureShowuntil.innerHTML = "Show Until: "+featureChildren[22];
			
  //Count and retrieve showuntil datetime, if it exists
	var featureShowUntilPre = featureChildren[22];
  
	if(featureShowUntilPre != undefined && featureShowUntilPre != null){
					
	 //Reformat the datetime so that there are no dashes, letters, or colons, remove any timezone info since we're going by the user's system time 
	 var replaceTimeZone = featureShowUntilPre.replace(/\D\d\D\d\d/gi, "");
	 var featureShowUntilDateRFMTPre = replaceTimeZone.replace(/\D/gi, "");
					   
	 //convert the datetime to a string
	 featureShowUntilDateRFMTPre.toString();
		
	 //remove the last four digits (timezone)
	 var featureShowUntilDateRFMT = featureShowUntilDateRFMTPre.substring(0, featureShowUntilDateRFMTPre.length - 4);
   
	 /*********************************************
		* Now we get the current date from the user's system clock and put it all
		* into one big string.  The format of the datetime will then match the format
		* that was created for the showuntil datetime.
		*********************************************/

	 var jsDT = new Date();
	 var realMonth = jsDT.getMonth() + 1;
	
	 if(realMonth < 10) {
		realMonth = "0" + realMonth;
	 }
					
	 var minutes = jsDT.getMinutes();
	 var seconds = jsDT.getSeconds();
	 var hours = jsDT.getHours();

	 if(hours < 10) {
		hours = "0" + hours;
	 }
	 
	 if(minutes < 10) {
	  minutes = "0" + minutes;
	 }
					
	 if(seconds < 10) {
		seconds = "0" + seconds;
	 }

	 var jsFullDateTime = jsDT.getFullYear() + '' + realMonth + '' + jsDT.getDate() + '' + hours + '' + minutes + '' + seconds;
		
	 //first convert the user's current system datetime to an integer (remember we made it a string in the previous function
	 var parsedJSFDT = parseInt(jsFullDateTime);
	
	 //convert the showuntil datetime to an integer (remember we made it a string in the previous function)
	 var parsedSUDR = parseInt(featureShowUntilDateRFMT);
					
	 //check to see if the user's system time is equal or greater than the showuntil datetime and if so, set the "container" div style display to none 
	 if(parsedJSFDT >= parsedSUDR) {
	  document.getElementById(divFeatureId).style.display="none";   
	 }
	
	}

 }		
	 
	 
 //Create a node for any media link that was defined, make the filesize look pretty (filesize should be in bytes in the Oister file, so we convert the display to KB or MB here)
 if(featureChildren[23]!="" && featureChildren[24]!="" && featureChildren[25]!=""){
	
  divFeatureMedia = document.createElement("div");
	divFeatureMedia.id = "media"+i;
	divFeatureMedia.className = "media";
	divFeature.appendChild(divFeatureMedia);
	
	var mediaKilobytes = featureChildren[24]/1024;
	var mediaMegabytes = mediaKilobytes/1024;
	var mediaSizeDisplayed;
	
	if(mediaMegabytes < 0.5){
	 mediaSizeDisplayed = (Math.round(mediaKilobytes*100)/100)+" KB";
	}
	else mediaSizeDisplayed = (Math.round(mediaMegabytes*100)/100)+" MB";
		
	divFeatureMedia.innerHTML = "Media Link: <a href=\""+featureChildren[25]+"\">"+featureChildren[25]+"</a> Media Type: "+featureChildren[23]+" Media Size: "+mediaSizeDisplayed;
 }
	
}

